<template>
  <div class="chart-settings-container">
    <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <!-- 基本设置 -->
      <a-form-item label="图表标题">
        <a-input v-model:value="options.title.text" placeholder="请输入图表标题" />
      </a-form-item>

      <!-- X轴设置 -->
      <a-collapse>
        <a-collapse-panel key="1" header="X轴设置">
          <a-form-item label="X轴名称">
            <a-input v-model:value="options.xAxis.name" placeholder="请输入X轴名称" />
          </a-form-item>
          <a-form-item label="X轴数据">
            <a-textarea 
              v-model:value="xAxisDataText" 
              :rows="3" 
              placeholder="请输入X轴数据，多个值用逗号分隔"
            />
          </a-form-item>
        </a-collapse-panel>
      </a-collapse>

      <!-- Y轴设置 -->
      <a-collapse>
        <a-collapse-panel key="1" header="Y轴设置">
          <a-form-item label="Y轴名称">
            <a-input v-model:value="options.yAxis.name" placeholder="请输入Y轴名称" />
          </a-form-item>
          <a-form-item label="Y轴数据">
            <a-textarea 
              v-model:value="yAxisDataText" 
              :rows="3" 
              placeholder="请输入Y轴数据，多个值用逗号分隔"
            />
          </a-form-item>
        </a-collapse-panel>
      </a-collapse>

      <!-- 视觉映射设置 -->
      <a-collapse>
        <a-collapse-panel key="1" header="视觉映射设置">
          <a-form-item label="最小值颜色">
            <a-input 
              v-model:value="visualMapMin.color" 
              type="color"
              style="width: 100px" 
            />
          </a-form-item>
          <a-form-item label="最大值颜色">
            <a-input 
              v-model:value="visualMapMax.color" 
              type="color"
              style="width: 100px" 
            />
          </a-form-item>
          <a-form-item label="最小值">
            <a-input-number 
              v-model:value="visualMapMin.value" 
              :min="0"
              style="width: 100px" 
            />
          </a-form-item>
          <a-form-item label="最大值">
            <a-input-number 
              v-model:value="visualMapMax.value" 
              :min="1"
              style="width: 100px" 
            />
          </a-form-item>
        </a-collapse-panel>
      </a-collapse>

      <!-- 数据矩阵编辑 -->
      <a-collapse>
        <a-collapse-panel key="1" header="数据矩阵编辑">
          <div class="matrix-container">
            <table class="matrix-table">
              <thead>
                <tr>
                  <th></th>
                  <th v-for="(xItem, xIndex) in xAxisData" :key="xIndex">
                    {{ xItem }}
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(yItem, yIndex) in yAxisData" :key="yIndex">
                  <td>{{ yItem }}</td>
                  <td v-for="(xItem, xIndex) in xAxisData" :key="xIndex">
                    <a-input-number 
                      v-model:value="dataMatrix[yIndex][xIndex]" 
                      :min="0"
                      style="width: 70px" 
                    />
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </a-collapse-panel>
      </a-collapse>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';

const props = defineProps({
  options: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['update:options']);

// 初始化默认配置
const initDefaultOptions = () => {
  if (!props.options.title) {
    props.options.title = { text: '热力图' };
  }

  if (!props.options.xAxis) {
    props.options.xAxis = { 
      type: 'category', 
      name: 'X轴',
      data: ['类别1', '类别2', '类别3'] 
    };
  }

  if (!props.options.yAxis) {
    props.options.yAxis = { 
      type: 'category', 
      name: 'Y轴',
      data: ['项目1', '项目2', '项目3'] 
    };
  }

  if (!props.options.visualMap) {
    props.options.visualMap = {
      min: 0,
      max: 100,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: '15%',
      inRange: {
        color: ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127']
      }
    };
  }

  if (!props.options.series || !props.options.series[0]) {
    props.options.series = [{
      type: 'heatmap',
      data: [],
      label: {
        show: true
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }];
  }
};

onMounted(() => {
  initDefaultOptions();
  updateDataMatrix();
});

// 处理X轴数据
const xAxisDataText = computed({
  get: () => {
    return props.options.xAxis?.data?.join(',') || '';
  },
  set: (value) => {
    const data = value.split(',').map((item: string) => item.trim()).filter((item: string) => item);
    props.options.xAxis.data = data;
    updateDataMatrix();
    emitUpdate();
  }
});

// 处理Y轴数据
const yAxisDataText = computed({
  get: () => {
    return props.options.yAxis?.data?.join(',') || '';
  },
  set: (value) => {
    const data = value.split(',').map((item: string) => item.trim()).filter((item: string) => item);
    props.options.yAxis.data = data;
    updateDataMatrix();
    emitUpdate();
  }
});

// 视觉映射设置
const visualMapMin = computed({
  get: () => {
    return {
      value: props.options.visualMap?.min || 0,
      color: props.options.visualMap?.inRange?.color?.[0] || '#ebedf0'
    };
  },
  set: (val) => {
    props.options.visualMap.min = val.value;
    if (!props.options.visualMap.inRange) {
      props.options.visualMap.inRange = { color: ['#ebedf0', '#196127'] };
    }
    props.options.visualMap.inRange.color[0] = val.color;
    emitUpdate();
  }
});

const visualMapMax = computed({
  get: () => {
    return {
      value: props.options.visualMap?.max || 100,
      color: props.options.visualMap?.inRange?.color?.[props.options.visualMap?.inRange?.color?.length - 1] || '#196127'
    };
  },
  set: (val) => {
    props.options.visualMap.max = val.value;
    if (!props.options.visualMap.inRange) {
      props.options.visualMap.inRange = { color: ['#ebedf0', '#196127'] };
    }
    
    const colorArr = props.options.visualMap.inRange.color;
    props.options.visualMap.inRange.color[colorArr.length - 1] = val.color;
    
    emitUpdate();
  }
});

// X轴和Y轴数据
const xAxisData = computed(() => props.options.xAxis?.data || []);
const yAxisData = computed(() => props.options.yAxis?.data || []);

// 数据矩阵
const dataMatrix = ref<number[][]>([]);

// 更新数据矩阵
const updateDataMatrix = () => {
  const yLength = yAxisData.value.length;
  const xLength = xAxisData.value.length;
  
  // 初始化数据矩阵
  const newMatrix: number[][] = [];
  
  // 从series中获取已有数据
  const existingData = props.options.series?.[0]?.data || [];
  
  for (let y = 0; y < yLength; y++) {
    newMatrix[y] = [];
    for (let x = 0; x < xLength; x++) {
      // 查找已有数据中是否存在对应坐标的值
      const existingItem = existingData.find(
        (item: [number, number, number]) => item[0] === x && item[1] === y
      );
      
      newMatrix[y][x] = existingItem ? existingItem[2] : 0;
    }
  }
  
  dataMatrix.value = newMatrix;
};

// 从序列数据生成矩阵数据
const matrixToSeriesData = computed(() => {
  const data: [number, number, number][] = [];
  
  dataMatrix.value.forEach((row, yIndex) => {
    row.forEach((value, xIndex) => {
      data.push([xIndex, yIndex, value]);
    });
  });
  
  return data;
});

// 更新图表配置并触发变更事件
const updateChartOptions = () => {
  // 深拷贝当前配置
  const newOptions = JSON.parse(JSON.stringify(props.options));
  
  // 确保series存在
  if (!newOptions.series) {
    newOptions.series = [{}];
  }
  
  // 确保series是数组
  if (!Array.isArray(newOptions.series)) {
    newOptions.series = [newOptions.series];
  }
  
  // 确保第一个系列存在
  if (!newOptions.series[0]) {
    newOptions.series[0] = {};
  }
  
  // 设置类型为热力图
  newOptions.series[0].type = 'heatmap';
  
  // 更新数据
  newOptions.series[0].data = matrixToSeriesData.value;
  
  // 触发更新事件
  emit('update:options', newOptions);
};

// 监听数据矩阵变化更新series数据
watch(dataMatrix, () => {
  updateChartOptions();
  emitUpdate();
}, { deep: true });

// 监听options变化更新数据矩阵
watch(() => props.options, () => {
  updateDataMatrix();
}, { deep: true });

// 发送更新事件
const emitUpdate = () => {
  emit('update:options', { ...props.options });
};
</script>

<style scoped>
.chart-settings-container {
  padding: 16px;
}

.matrix-container {
  overflow-x: auto;
  max-width: 100%;
  padding: 8px 0;
}

.matrix-table {
  border-collapse: collapse;
  width: 100%;
}

.matrix-table th,
.matrix-table td {
  padding: 6px;
  text-align: center;
}

.matrix-table thead th {
  background-color: #f5f5f5;
}

.matrix-table tr td:first-child {
  background-color: #f5f5f5;
  font-weight: bold;
}
</style> 